package com.example.runnable;

import com.example.utils.TextFileReader;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

import static com.example.runnable.Constants.W_PATH;

@Component
@ConditionalOnProperty(name = "run-env",havingValue = "test04")
public class Test04 implements ApplicationRunner {

    @Resource
    SqlSessionFactory sqlSessionFactory;

    @Resource
    HikariDataSource hikariDataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Connection connection = hikariDataSource.getConnection();
//        connection.setAutoCommit(false);
        String sql = "insert into T_BOND_BASIS_INFO values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        long begin=System.currentTimeMillis();
        TextFileReader fileReader = null;
        try {
            fileReader = new TextFileReader(W_PATH,"utf-8");
            List<String> list=null;
            int i=1;
            while (fileReader.hasNext()){
                long start = System.currentTimeMillis();
                list = fileReader.readNextLines(100);
                for (String s : list) {
                    String[] data = s.split(",");
                    for (int j = 1; j <=data.length ; j++) {
                        statement.setString(j,data[j-1]);
                    }
                    statement.addBatch();
                    statement.executeBatch();
                    statement.clearParameters();
                }
                long end = System.currentTimeMillis();
                System.out.println("总耗时:"+(end-begin)/1000+",耗时:"+(end-start)+";批次:"+(i)*100);
                list.clear();
                i++;

            }
            System.out.println("耗时:"+(System.currentTimeMillis()-begin));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileReader!=null){
                fileReader.close();
            }
        }
    }

    private String values(String str){
        return str==null? "":str;
    }
}
